package com.corner.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.corner.R;
import com.corner.app.App;
import com.corner.app.GlobalParams;
import com.corner.model.cornerservice.domain.Info;
import com.corner.model.cornerservice.domain.User;
import com.corner.presenter.imp.ChannelPresenter;
import com.corner.ui.adapter.InfoAdapter;
import com.corner.ui.base.BaseActivity;
import com.corner.ui.parcel.PoiItem;
import com.corner.ui.view.IChannelView;
import com.corner.utils.AppManager;
import com.corner.utils.CommonUtil;
import com.corner.utils.DateFormatUtil;
import com.corner.utils.DialogUtil;
import com.corner.utils.IntentUtil;
import com.corner.utils.SoftInputUtil;
import com.corner.utils.ToastUtil;
import com.corner.utils.view.FindView;
import com.corner.utils.view.InjectViewUtils;
import com.corner.utils.view.InputBox;
import com.corner.utils.view.MainActionBar;
import com.corner.utils.view.widget.XListView;
import com.facebook.drawee.view.SimpleDraweeView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/7/24，22.39.
 * 描述：
 */
public class ChannelActivity extends BaseActivity<ChannelPresenter> implements IChannelView, View.OnClickListener {

    public static final String INTENT_ID = "INTENT_ID";
    public static final String LOCATION_ID = "locationId";
    public static final String LOCATION_NAME = "locationName";
    public static final int PICTURE = 0;
    public static final int CAMERA = 1;
    public static final int PICVOICE = 2;
    private static final int SELECT_PIC_RECT = 3;
    private static final int RECORD_AUDIO_FOR_PIC = 4;
    @FindView(R.id.ll_create_info_send_progress)
    private LinearLayout llProgress;
    @FindView(R.id.view_create_info_input_box)
    private InputBox inputBox;
    @FindView(R.id.iv_input_window_pic_show)
    private SimpleDraweeView ivPrePic;
    @FindView(R.id.ll_input_window_pic_show)
    private RelativeLayout llPreShow;
    @FindView(R.id.tv_input_window_pic_delete)
    private TextView tvPreRemove;
    private MainActionBar actionBar;
    @FindView(R.id.lv_location_info)
    private XListView lvInfos;
    private String currentPicPath;
    private InfoAdapter adapter;
    private String currAudioPic;
    private int currRequestCode;
    private float[] scales;
    private String cameraPicPath;
    private Long locationId;
    private TextView tvAttentionTitle;
    private TextView tvAttentionCancel;
    private TextView tvAttentionEnsure;
    private Dialog attentionDialog;
    private Boolean isAttention;
    private PoiItem poiItem;
    private String name;
    private View boottom;

    @Override
    protected ChannelPresenter createP() {
        return new ChannelPresenter();
    }

    @Override
    protected void setOnClick() {
        actionBar.btnLeft.setOnClickListener(this);
        actionBar.ivRight.setOnClickListener(this);
        inputBox.tvSend.setOnClickListener(this);
        inputBox.tvImgVoc.setOnClickListener(this);
        inputBox.tvCamera.setOnClickListener(this);
        inputBox.tvPic.setOnClickListener(this);
        inputBox.etChatInfo.requestFocus();
        SoftInputUtil.hideSoftInput(this, inputBox.etChatInfo);
        tvPreRemove.setOnClickListener(this);
        lvInfos.setPullLoadEnable(false);
        lvInfos.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                presenter.requestInfos(locationId);
            }

            @Override
            public void onLoadMore() {
                presenter.loadMoreInfos();
            }
        });
        lvInfos.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                inputBox.llImgVocHide.setVisibility(View.GONE);
                SoftInputUtil.hideSoftInput(ChannelActivity.this, inputBox.etChatInfo);
                return false;
            }
        });
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        int intentId = intent.getIntExtra(INTENT_ID, 0);
        if (intentId == SearchLocationActivity.SEARCH_LOCATION) {
            poiItem = intent.getParcelableExtra(SearchLocationActivity.SEARCH_LOCATION_S);
            if (poiItem != null) {
                actionBar.tvMiddle.setText(poiItem.name);
                presenter.requestLocationByPoiItem(poiItem);
            } else {
                name = intent.getStringExtra(SearchLocationActivity.SEARCH_LOCATION_S_NAME);
                actionBar.tvMiddle.setText(name);
                presenter.requestLocationByName(name);
            }
        } else {
            locationId = intent.getLongExtra(LOCATION_ID, 0);
            String locationName = intent.getStringExtra(LOCATION_NAME);
            if (!TextUtils.isEmpty(locationName))
                actionBar.tvMiddle.setText(intent.getStringExtra(LOCATION_NAME));
            else {
                presenter.requestLocationByLocationId(locationId);
            }
        }
        adapter = new InfoAdapter(new ArrayList<Info>(), this, false);
        lvInfos.setAdapter(adapter);
        if (locationId!=null) {
            lvInfos.autoRefresh();
        }
    }

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_channel);
    }

    @Override
    public void showRefreshInfos(List<Info> infos) {
        adapter.changeList(infos);
    }

    @Override
    public void showRefreshComplete() {
        lvInfos.stopRefresh();
    }

    @Override
    public void setLoadMoreEnable(boolean hasMore) {
        lvInfos.setPullLoadEnable(hasMore);
    }

    @Override
    public void showLoadMoreComplete() {
        lvInfos.stopLoadMore();
    }

    @Override
    public void showLoadMoreInfos(List<Info> infos) {
        adapter.changeList(infos);
    }


    @Override
    public void initView() {
        super.initView();
        inputBox.setActivity(this);
        inputBox.setIsAudioEnable(false);
        inputBox.tvImgVoc.setVisibility(View.GONE);

        actionBar = new MainActionBar(this);
        actionBar.initActionBarButton();
        actionBar.btnLeft.setVisibility(View.VISIBLE);
        actionBar.ivRight.setVisibility(View.VISIBLE);
        actionBar.ivRight.setImageResource(R.drawable.channel_nav_plus);
        actionBar.tvMiddle.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);//下划线
        actionBar.tvMiddle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.location_list_item_name_szie));

        if (boottom == null) {
            boottom = View.inflate(this, R.layout.view_lv_bottom, null);
            AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                    getResources().getDimensionPixelSize(R.dimen.lv_info_footer_height));
            boottom.setLayoutParams(layoutParams);
        } else {
            if (boottom.getParent() != null) {
                ((ListView) boottom.getParent()).removeHeaderView(boottom);
            }
        }
        lvInfos.addFooterView(boottom);
    }

    @Override
    public void onClick(View v) {
        if (v == inputBox.tvSend) {
            if (currentPicPath == null) {
                if (!TextUtils.isEmpty(inputBox.etChatInfo.getText())) {
                    sendInfo(inputBox.etChatInfo.getText().toString(), null,
                            null, Info.T);
                }
            } else {
                if (!TextUtils.isEmpty(currAudioPic)) {
                    sendInfo(inputBox.etChatInfo.getText().toString(), currentPicPath, currAudioPic, Info.AP);
                } else if (!TextUtils.isEmpty(inputBox.etChatInfo.getText())) {
                    sendInfo(inputBox.etChatInfo.getText().toString(),
                            currentPicPath, null, Info.TP);
                } else {
                    sendInfo(inputBox.etChatInfo.getText().toString(),
                            currentPicPath, null, Info.P);
                }
                llPreShow.setVisibility(View.GONE);
                currentPicPath = null;
            }
            clearInputBox();
            SoftInputUtil.hideSoftInput(this, inputBox.etChatInfo);
        } else if (v == inputBox.tvImgVoc || v == inputBox.tvPic) {
            // 拿照片
            Intent intent_file = IntentUtil.getPicIntent();
            if (v == inputBox.tvImgVoc) {
                this.currRequestCode = PICVOICE;
            } else {
                this.currRequestCode = PICTURE;
            }
            startActivityForResult(intent_file, currRequestCode);
        } else if (v == inputBox.tvCamera) {
            // 照相
            Intent intent_camera;
            try {
                cameraPicPath = GlobalParams.APPFIEPATH + "/camera/"
                        + System.currentTimeMillis() + ".jpg";
                intent_camera = IntentUtil.getCameraIntent(cameraPicPath);
                this.currRequestCode = CAMERA;
                startActivityForResult(intent_camera, this.currRequestCode);
            } catch (IOException e) {
                CommonUtil.showSDcardError(getApplicationContext());
                e.printStackTrace();
            }
        } else {
            switch (v.getId()) {
                case R.id.tv_input_window_pic_delete:
                    llPreShow.setVisibility(View.GONE);
                    currentPicPath = null;
                    break;
                case R.id.btn_actionbar_left:
                    AppManager.getInstance().finishActivity(this);
                    break;
                case R.id.iv_actionbar_right:
                    showAttentionDialog();
                    break;
                case R.id.tv_attention_cancel:
                    DialogUtil.hideDialog(attentionDialog);
                    break;
                case R.id.tv_attention_ensure:
                    DialogUtil.hideDialog(attentionDialog);
                    if (isAttention) {
                        presenter.cancelAttention();
                    } else {
                        presenter.attention();
                    }
                    break;
            }
        }
    }

    private void showAttentionDialog() {
        excuteTaskWhenNetOk(new Task() {
            @Override
            public void onExcute() {
                presenter.requestIsAttention();
            }
        });
    }


    /**
     * 创建Info Bean
     *
     * @param text      文本
     * @param imagePath 图片
     * @param audioPath 语音
     * @param type      类型
     * @param scales    图片显示的尺寸
     * @return
     */
    private Info createInfo(String text, String imagePath, String audioPath, int type, float[] scales) {

        Info info = new Info();
        if (!TextUtils.isEmpty(text)) {
            info.setText(text);
        }
        if (!TextUtils.isEmpty(imagePath)) {
            info.setImagePath(imagePath);
        }
        if (!TextUtils.isEmpty(audioPath)) {
            info.setAudioPath(audioPath);
        }
        if (scales != null) {
            info.setScale(scales);
        }
        User currentUser = User.getCurrentUser();
        info.setUser(currentUser);
        info.setType(type);
        return info;
    }

    /**
     * 发送Info
     *
     * @param text
     * @param imagePath
     * @param audioPath
     * @param type
     */
    private void sendInfo(final String text, final String imagePath,
                          final String audioPath, final int type) {
        Info info = createInfo(text, imagePath,
                audioPath, type, scales);
        sendInfo(info, false);
    }

    private void sendInfo(Info info, boolean isReSend) {
        if (locationId != null) {
            presenter.sendInfo(info, isReSend);
        } else if (locationId == null) {
            if (poiItem != null)
                presenter.sendInfo(info, poiItem, isReSend);
            else if (name != null)
                presenter.sendInfo(info, name, isReSend);
        }
    }


    @Override
    public void showSending(Info info, boolean isReSend) {
        View sendProgress = null;
        SendProgressHolder holder = null;
        if (isReSend) {
            sendProgress = llProgress.findViewWithTag(info.id);
            holder = (SendProgressHolder) sendProgress.getTag(R.integer.send_progress_view_holder);
        } else {
            sendProgress = View.inflate(getApplicationContext(),
                    R.layout.view_send_info_progress, null);
            holder = new SendProgressHolder();
            info.id = DateFormatUtil.getCurrentTimeInMills() + "";
            sendProgress.setTag(info.id);
            sendProgress.setTag(R.integer.send_progress_view_holder, holder);
            InjectViewUtils.injectView(holder, sendProgress, this);
        }
        switch (info.getType()) {
            case Info.T:
                holder.tvText.setText(info.getText());
                holder.ivPic.setVisibility(View.GONE);
                break;
            case Info.A:
                holder.ivPic.setVisibility(View.GONE);
                holder.tvText.setText(R.string.send_info_notice_text_audio);
                break;
            case Info.P:
                holder.ivPic.setVisibility(View.VISIBLE);
                holder.ivPic.setImageDrawable(Drawable
                        .createFromPath(info.getImagePath()));
                break;
            case Info.AP:
                holder.ivPic.setVisibility(View.VISIBLE);
                holder.ivPic.setImageDrawable(Drawable
                        .createFromPath(info.getImagePath()));
                holder.tvText
                        .setText(R.string.send_info_notice_text_audio_pic);
                break;
            case Info.TP:
                holder.tvText.setText(info.getText());
                holder.ivPic.setVisibility(View.VISIBLE);
                holder.ivPic.setImageDrawable(Drawable
                        .createFromPath(info.getImagePath()));
                break;
        }
        initHolderCommon(holder);
        if (!isReSend)
            llProgress.addView(sendProgress,
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
    }

    /**
     * 初始化SendProgressHolder
     *
     * @param holder
     */
    private void initHolderCommon(SendProgressHolder holder) {
        holder.tvNotice.setText(R.string.send_info_sending);
        holder.tvResend.setVisibility(View.GONE);
        holder.tvDelete.setVisibility(View.GONE);
        holder.tvNotice.setTextColor(getResources().getColor(
                R.color.common_blue));
        holder.tvNoticeColor.setBackgroundResource(R.color.common_blue);
    }

    @Override
    public void showSendError(final Info info) {
        final View sendProgress = llProgress.findViewWithTag(info.id);
        final SendProgressHolder holder = (SendProgressHolder) sendProgress.getTag(R.integer.send_progress_view_holder);
        holder.tvResend.setVisibility(View.VISIBLE);
        holder.tvDelete.setVisibility(View.VISIBLE);
        holder.tvNotice.setText(R.string.send_info_notice_failed);
        holder.tvNotice.setTextColor(getResources().getColor(
                R.color.red));
        holder.tvNoticeColor.setBackgroundResource(R.color.red);
        if (holder.resendListener == null) {
            holder.resendListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initHolderCommon(holder);
                    sendInfo(info, true);
                }
            };
            holder.tvResend.setOnClickListener(holder.resendListener);
        }
        if (holder.deleteListener == null) {
            holder.deleteListener = new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    llProgress.removeView(sendProgress);
                }
            };
            holder.tvDelete.setOnClickListener(holder.deleteListener);
        }
    }

    @Override
    public void sendSucess(Info info) {
        View sendProgress = llProgress.findViewWithTag(info.id);
        llProgress
                .removeView(sendProgress);
        presenter.requestInfos(locationId);
    }

    @Override
    public void showError(String message) {
        ToastUtil.showCustomToastInRelease(App.application, message);
    }

    @Override
    public void requestAttentionSucess(Boolean aBoolean) {
        if (attentionDialog == null) {
            //自己发的内容
            attentionDialog = DialogUtil.showDiaLog(R.layout.dialog_attention_channel, this);
            tvAttentionEnsure = (TextView) attentionDialog.findViewById(R.id.tv_attention_ensure);
            tvAttentionCancel = (TextView) attentionDialog.findViewById(R.id.tv_attention_cancel);
            tvAttentionTitle = (TextView) attentionDialog.findViewById(R.id.tv_attention_title);
            tvAttentionEnsure.setOnClickListener(this);
            tvAttentionCancel.setOnClickListener(this);
        } else {
            attentionDialog.show();
        }
        isAttention = aBoolean;
        if (isAttention) {
            tvAttentionTitle.setText(getString(R.string.dialog_cancel_attention_is_ok));
            tvAttentionEnsure.setText(getString(R.string.dialog_cancel_attention_ok));
        } else {
            tvAttentionTitle.setText(getString(R.string.dialog_attention_is_ok));
            tvAttentionEnsure.setText(getString(R.string.dialog_attention_ok));
        }
    }

    @Override
    public void cancelSucess() {
        ToastUtil.showCustomToastInRelease(App.application, getString(R.string.cancel_attention_sucess));
    }

    @Override
    public void attentionSucess() {
        ToastUtil.showCustomToastInRelease(App.application, getString(R.string.attention_sucess));
    }

    @Override
    public void setLocationName(String locationName) {
        actionBar.tvMiddle.setText(locationName);
    }

    @Override
    public void setLocationId(Long objectId) {
        locationId = objectId;
        presenter.requestInfos(locationId);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RECORD_AUDIO_FOR_PIC) {
            if (resultCode == Record4Pic.RESULT_OK) {
                currAudioPic = data.getStringExtra(Record4Pic.AUDIO_PATH);
                preViewPic();
            } else if (resultCode == Record4Pic.RESULT_CANCEL) {
                currentPicPath = null;
            } else if (resultCode == Record4Pic.RESULT_RESELECT) {
                currentPicPath = null;
                startActivityForResult(IntentUtil.getPicIntent(),
                        currRequestCode);
            }
        } else if (requestCode == SELECT_PIC_RECT) {
            if (resultCode == SelectPicShowRectActivity.OK) {
                scales = data
                        .getFloatArrayExtra(SelectPicShowRectActivity.SCALE);
                currentPicPath = data
                        .getStringExtra(SelectPicShowRectActivity.PICTUREPATH);
                if (currRequestCode == PICVOICE) {
                    data.putExtra(Record4Pic.PICTUREPATH, currentPicPath);
                    data.setClass(getApplicationContext(), Record4Pic.class);
                    startActivityForResult(data, RECORD_AUDIO_FOR_PIC);
                } else {
                    preViewPic();
                }
            } else if (resultCode == SelectPicShowRectActivity.CANCEL) {
                Intent intent_file = IntentUtil.getPicIntent();
                startActivityForResult(intent_file, currRequestCode);
            }
        } else {
            String picturePath = null;
            if (requestCode == PICTURE || requestCode == PICVOICE) {
                if (data == null)
                    return;
                Uri selectedImage = data.getData();
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = this.getContentResolver().query(selectedImage,
                        filePathColumns, null, null, null);
                if (c!=null) {
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    picturePath = c.getString(columnIndex);
                    c.close();
                }else{
                    ToastUtil.showCustomToastInRelease(App.application,"获取相册图片失败");
                }
            } else if ((requestCode == CAMERA)
                    && (resultCode == Activity.RESULT_OK)) {
                picturePath = cameraPicPath;
            }
            if (picturePath != null) {
                Intent intent = new Intent(getApplicationContext(),
                        SelectPicShowRectActivity.class);
                intent.putExtra(SelectPicShowRectActivity.PICTUREPATH,
                        picturePath);
                intent.putExtra(SelectPicShowRectActivity.INTENT_ID,
                        SelectPicShowRectActivity.IMAGE);
                startActivityForResult(intent, SELECT_PIC_RECT);
            }
        }
    }

    /**
     * 预览图片
     */
    private void preViewPic() {
        llPreShow.setVisibility(View.VISIBLE);
        ivPrePic.setImageURI(Uri.fromFile(new File(currentPicPath)));
        inputBox.initWigt();
        inputBox.tvSend.setVisibility(View.VISIBLE);
        inputBox.etChatInfo.setVisibility(View.VISIBLE);
    }

    /**
     * 清空输入框
     */
    private void clearInputBox() {
        inputBox.clearInputBox();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (adapter != null) {
            adapter.onDestroy();
        }
    }

    /**
     * 发送进度提示的Holder
     *
     * @author Administrator
     */
    public static class SendProgressHolder {
        @FindView(R.id.tv_send_info_text)
        public TextView tvText;
        @FindView(R.id.tv_send_info_notice)
        public TextView tvNotice;
        @FindView(R.id.iv_send_info_progress_pic)
        public ImageView ivPic;
        @FindView(R.id.tv_send_info_resend)
        public TextView tvResend;
        @FindView(R.id.tv_send_info_content_delete)
        public TextView tvDelete;
        @FindView(R.id.tv_send_info_notice_color)
        public TextView tvNoticeColor;
        public long id;
        private View.OnClickListener resendListener;
        private View.OnClickListener deleteListener;
    }
}
